import axios from 'axios'
import qs from 'qs'
import {
  Toast,
  Indicator
  // MessageBox
} from 'mint-ui';
import router from '../router/index';
import CONFIG from "./CONFIG.js";

axios.defaults.baseURL = CONFIG.URL.APIHOST; //配置接口地址
axios.defaults.timeout = CONFIG.URL.APITIME; // 超时时间
let locationURL = CONFIG.URL.APIHOSTLOCA; //省市区接口(及部分接口)
axios.create({
  withCredentials: true // 跨域
})


//http request 拦截器
axios.interceptors.request.use(
  config => {
    Indicator.open('加载中...');
    // config.data = qs.stringify(config.data);
    // config.headers = {
    //     'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    //     'X-Requested-With': 'XMLHttpRequest'
    // }
    // if(config.method === 'get'){
    //     config.headers['Accept'] = "application/json";
    // }
    // let token = localStorage.getItem('token');
    // if (token) {
    //     config.headers['token'] = token
    // }
    return config;
  },
  error => {
    return Promise.reject(err);
  }
);


//http response 拦截器
axios.interceptors.response.use(
  response => {
    if (response.data.errCode == 2) {
      router.push({
        path: "/login",
        querry: {
          redirect: router.currentRoute.fullPath
        } //从哪个页面跳转
      })
    }
    return response;
  },
  error => {
    return Promise.reject(error)
  }
);

function errorState(response) {
  Indicator.close(); //隐藏loading
  // 如果http状态码正常，则直接返回数据
  if (response && (response.status === 200 || response.status === 304 || response.status === 400) && response.data.code === 0) {
    return response
    // 如果不需要除了data之外的数据，可以直接 return response.data
  } else {
    Toast({
      message: '网络异常',
      position: 'bottom',
      duration: 3000
    });
  }
}

function successState(response) {
  Indicator.close(); //隐藏loading

  //统一判断后端返回的错误码
  if (response && response.data.code === 501) {
    Toast({
      message: '登陆已过期,请重新登陆!',
      position: 'bottom',
      duration: 3000
    });

    router.push({
      path: "/login"
    });

  } else if (response.data.code !== 0 && response.data.code !== 504) {
    Toast({
      message: response.data.msg || '网络异常',
      position: 'bottom',
      duration: 3000
    });
  }
}

function httpServer(opts, data, uploadImg = 0) {

  let Public = { //公共参数  
    // 'srAppid': ""
  }

  let httpDefaultOpts = { //http默认配置  
    method: opts.method,
    // baseURL,
    url: opts.url,
    // withCredentials: true,
    // timeout: 20000,
    params: Object.assign(Public, data),
    data: qs.stringify(Object.assign(Public, data)),
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
  }
  // 省市区接口
  if (data.location) {
    httpDefaultOpts['baseURL'] = locationURL
  }

  let token = localStorage.getItem('token');
  if (token) {
    httpDefaultOpts.headers['token'] = token
  }

  if (opts.method === 'get') {
    httpDefaultOpts.headers['Accept'] = "application/json";
    delete httpDefaultOpts.data
  } else {
    delete httpDefaultOpts.params;
    if (uploadImg) {
      httpDefaultOpts.headers['Content-Type'] = "multipart/form-data";
    }
  }

  // console.log('请求参数打印=='+JSON.stringify(httpDefaultOpts));

  let promise = new Promise(function (resolve, reject) {
    axios(httpDefaultOpts).then(
      res => {
        // console.log('请求成功==' + JSON.stringify(res));
        successState(res);
        if (res.data.code === 0)
          return resolve(res.data);
      }
    ).catch(
      res => {
        console.log('请求失败===' + JSON.stringify(res));
        errorState(res)
        return reject(res)
      }
    )
  })
  return promise
}


export default {
  post(url, data = {}) {
    return httpServer({
      method: 'post',
      url: url
    }, data)
  },
  get(url, params = {}) {
    return httpServer({
      method: 'get',
      url,
    }, params)
  },
  img(url, data = {}) {
    return httpServer({
      method: 'post',
      url,
    }, data, 1)
  },
  put(url, data = {}) {
    return httpServer({
      method: 'put',
      url: url
    }, data)
  },
  del(url, params) {
    return httpServer({
      method: 'del',
      url: url
    }, params)
  },
  fetch(ops, data = {}) {
    return httpServer({
      ops
    }, data)
  },
  all(arr, func = () => {}) {
    return axios.all(arr)
      .then(axios.spread((acct, perms) => {
        // 两个请求现在都执行完成
        return func(acct, perms)
      }));
  }
}
